package com.atguigu.day03;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author Felix
 * @date 2024/4/1
 * 该案例演示了转换算子-flatMap
 * 需求： 从指定的网络端口读取一行字符串，并将字符串拆分为一个个单词，并转换为二元组
 */
public class Flink11_Trans_FlatMap {
    public static void main(String[] args) throws Exception {
        //TODO 1.指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //TODO 2.准备数据
        DataStreamSource<String> socketDS = env.socketTextStream("hadoop102", 8888);
        //TODO 3.将字符串拆分为一个个单词，并转换为二元组
         /*SingleOutputStreamOperator<String> idDS = wsDS.map(
                new MapFunction<WaterSensor, String>() {
                    @Override
                    public String map(WaterSensor ws) throws Exception {
                        return ws.getId();
                    }
                }
        );*/
        SingleOutputStreamOperator<Tuple2<String, Long>> flatMapDS = socketDS.flatMap(
                new FlatMapFunction<String, Tuple2<String, Long>>() {
                    @Override
                    public void flatMap(String lineStr, Collector<Tuple2<String, Long>> out) throws Exception {
                        String[] words = lineStr.split(" ");
                        for (String word : words) {
                            out.collect(Tuple2.of(word, 1L));
                        }
                    }
                }
        );

        //TODO 4.打印
        flatMapDS.print();
        //TODO 5.提交作业
        env.execute();
    }
}
